/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.controller

import org.ibiblio.terasaur.bt.Torrent
import org.ibiblio.terasaur.item.Item
import org.joda.time.DateTime
import org.ibiblio.terasaur.search.DateHelper

class TorrentMixin {
    /**
     * Get Torrent instance for the current request.  Check:
     *  - publication date
     *  - item publication date
     *  - item deleted value
     *
     * Returns an Torrent if everything checks out, null if the item isn't
     * accessible by the current user.
     *
     * @return Torrent
     */
    public Torrent getTorrentInstance() {
        Torrent torrent = null
        Item item = null

        String infoHash = findInfoHashParam()
        if (infoHash) {
            torrent = Torrent.get(infoHash)
        }

        // Torrent visibility is determined by the item
        if (torrent) {
            item = getItemInstanceForId(torrent.item.id)
            if (!item) {
                torrent = null
            }
        }

        return torrent
    }

    public String findInfoHashParam() {
        String infoHash = null
        if (params.id && params.id.size() == 40) {
            infoHash = params.id
        } else if (params.infoHash && params.infoHash.size() == 40) {
            infoHash = params.infoHash
        }
        return infoHash
    }
}
